package ymqtt

import (
	"context"
	"fmt"
	"sync"
	"time"
)

const (
	defaultMsgExpire  = 10 * time.Second
	defaultTickerTime = 30 * time.Second
)

type Msg struct {
	Time   time.Time `json:"time"`
	Result bool      `json:"result"`
}

type result struct {
	*operate
	ctx      context.Context
	ttl      time.Duration
	ticker   *time.Ticker
	messages map[string]Msg
}

func (r *result) write(key string, msg Msg) {
	r.Lock(func() {
		if r.messages != nil {
			r.messages[key] = msg
		}
	})
	fmt.Printf("clientId:%s message:%+v \r\n", key, r.messages)
}

func (r *result) del(key string) {
	r.Lock(func() {
		delete(r.messages, key)
	})
}

func (r *result) clear() {
	r.Lock(func() {
		r.messages = nil
	})
}

func (r *result) read(key string) *Msg {
	var msg *Msg
	if message, ok := r.messages[key]; ok {
		msg = &message
		r.del(key)
	}

	return msg
}

func (r *result) expire() {
	for _ = range r.ticker.C {
		t := time.Now()
		for key, msg := range r.messages {
			if t.Sub(msg.Time) > r.ttl {
				r.del(key)
			}
		}
	}
}

func (r *result) start() {
	defer r.clear()
	defer r.ticker.Stop()
	go r.expire()

	for {
		select {
		case <-r.ctx.Done():
			break
		}
	}
}

func newResult(ctx context.Context) *result {
	return &result{
		operate:  &operate{lock: sync.Mutex{}},
		ttl:      defaultMsgExpire,
		ctx:      ctx,
		ticker:   time.NewTicker(defaultTickerTime),
		messages: make(map[string]Msg),
	}
}
